<?php
namespace User\Controller;

use Think\Controller;

class EnrollRecordController extends UserController
{
    public function delete()
    {
        $items = I( "post.items", array(-1), "" );
        $condition['id'] = array( "in", $items );
        $condition['token'] = $this->wxuser['token'];
        $deleted = D( "enrollRecord" )->where( $condition )->delete();
        if( $deleted ){
            $this->success( "删除成功" );
        }else{
            $this->error( "删除失败" );
        }
    }

    public function download()
    {
        $options = I( "post.file", 'excel', "" );
        $items = I( "post.items", array(), "" );
        $enroll = I( "get.enroll", -1, "" );
        $condition['token'] = $this->wxuser['token'];
        if( count( $items ) ){
            $condition['id'] = array( "in", $items );
        }
        $condition['eid'] = $enroll;

        $en_fields = array( "id", "username", "telephone", "company" );
        $zh_fields = array( "编号", "姓名", "手机", "公司" );
        $datas = D( "enrollRecord" )->where( $condition )->field( $en_fields )->select();
        $enroll = D( "enroll" )->where( array( "id" => $enroll, "token" => $this->wxuser['token'] ) )->find();
        if( !count( $enroll ) ){
            $this->error( "没有找到相关活动信息" );
        }

        if( $options === "excel" ){
            $this->exportexcel( $datas, $zh_fields, $enroll['title'] );
        }
    }

    private function exportexcel($data=array(),$title=array(),$filename='report'){
        header("Content-type:application/octet-stream");
        header("Accept-Ranges:bytes");
        header("Content-type:application/vnd.ms-excel");
        header("Content-Disposition:attachment;filename=".$filename.".xls");
        header("Pragma: no-cache");
        header("Expires: 0");
        //导出xls 开始
        if (!empty($title)){
            foreach ($title as $k => $v) {
                $title[$k]=iconv("UTF-8", "GB2312",$v);
            }
            $title= implode("\t", $title);
            echo "$title\n";
        }
        if (!empty($data)){
            foreach($data as $key=>$val){
                foreach ($val as $ck => $cv) {
                    $data[$key][$ck]=iconv("UTF-8", "GB2312", $cv);
                }
                $data[$key]=implode("\t", $data[$key]);

            }
            echo implode("\n",$data);
        }
    }
}
